namespace mplat {
    export class WxShare {

        /** 分享列表的数据配置 */
        protected _shareList: IShareInfo[];
        /** 默认分享的idx，小于0则是随机从sharelist中获取 */
        protected _defaultShareIdx: number = -1;
        /** 分享的默认query */
        protected _shareDefaultString: string = '';
        /** 分享失败的提示 */
        protected _shareFailTips: IShowModalInfo[] = [];

        /** 本次分享总共用的时间戳(用来判断是否能分享成功) */
        protected _shareTotalTime = 0;

        /** 本次分享开始的时间戳 */
        protected _shareStartTime = 0;
        /** 本次分享已经进行的次数 */
        protected _shareCount = 0;
        /** 最少3秒之后，算成功 */
        protected _shareMinTime = 3;
        /** 最少2次就算成功 */
        protected _shareMinCount = 2;
        /** 分享结束后，默认都会执行的回调 */
        protected _shareDefaultSuccess: () => void;
        protected _shareDefaultFail: () => void;
        protected _shareDefaultComplete: () => void;

        protected _successFun: () => void;// 分享成功的当前回调
        protected _failFun: () => void;// 分享失败的当前回调
        protected _shareContent: any;// 临时生成的分享数据
        protected _readyShare = false;

        constructor() {

            wx.onShow(this._shareHandler.bind(this));

        }

        setShareFailTips(tips: IShowModalInfo[]) {
            this._shareFailTips = tips;
        }

        setShareInfo(shareList: IShareInfo[], defaultShareIdx?: number, minTime?: number, minCount?: number) {
            if (!isNaN(defaultShareIdx)) {
                this._defaultShareIdx = defaultShareIdx;
            }
            if (!isNaN(minTime)) {
                this._shareMinTime = minTime;
            }
            if (!isNaN(minCount)) {
                this._shareMinCount = minCount;
            }
            this._shareList = shareList;
        }

        setShareDefaultComplete(success?: () => void, fail?: () => void, complete?: () => void) {
            this._shareDefaultSuccess = success;
            this._shareDefaultFail = fail;
            this._shareDefaultComplete = complete;
        }

        setShareDefaultData(data: any) {
            this._shareDefaultString = object2Query(data);
        }

        showShareMenu(withShareTicket?: boolean) {
            if (!this._shareList || !this._shareList.length) {
                debugLog('未设置分享数据')
                return;
            }
            wx.showShareMenu({ withShareTicket: !!withShareTicket });

            let shareFun: any;
            if (wx['aldOnShareAppMessage']) {
                shareFun = wx['aldOnShareAppMessage'];
            } else {
                shareFun = wx.onShareAppMessage;
            }
            let idx = this._defaultShareIdx;
            if (this._defaultShareIdx < 0) {
                idx = Math.floor(Math.random() * this._shareList.length);
            }
            let param = this._shareList[idx]
            let content = {
                title: param.title, imageUrlId: param.imageUrlId, imageUrl: param.imageUrl,
                query: this._shareDefaultString
            }
            shareFun(() => {
                return content;
            });
        }
        shareAppMessage(param?: IShareInfo, data?: any, success?: () => void, fail?: () => void) {
            if (!param) {
                if (!this._shareList || !this._shareList.length) {
                    debugLog('未设置分享数据')
                    return;
                }
                let idx = Math.floor(Math.random() * this._shareList.length);
                param = this._shareList[idx]
            }
            let query = this._shareDefaultString;
            if (data) {
                let temp = object2Query(data);
                if (query != "") {
                    query += "&"
                }
                query += temp
            }
            this._shareContent = {
                title: param.title, imageUrlId: param.imageUrlId, imageUrl: param.imageUrl,
                query: query
            }

            this._successFun = success;
            this._failFun = fail;
            this._readyShare = true;

            this._callShare()
        }

        protected _callShare() {
            if (!this._shareContent) {
                debugLog('分享数据错误');
                return;
            }

            this._shareStartTime = Date.now();
            this._shareCount++;

            let shareFun: any;
            if (wx['aldShareAppMessage']) {
                shareFun = wx['aldShareAppMessage'];
            } else {
                shareFun = wx['shareAppMessage'];
            }
            shareFun(this._shareContent);

        }

        protected _shareHandler(res) {
            if (!this._readyShare) return;
            debugLog('share hander')

            if (this._shareCount >= this._shareMinCount) {
                this._shareSuccess();
            } else {
                let dt = Date.now() - this._shareStartTime;
                if (this._shareTotalTime <= 0) {
                    this._shareTotalTime = dt;
                } else {
                    this._shareTotalTime += dt;
                }
                debugLog('分享到现在总共已经过去了', this._shareTotalTime, 'ms');
                if (this._shareTotalTime < this._shareMinTime * 1000) {
                    if (!this._shareFailTips || !this._shareFailTips.length) {
                        // 不需要执行失败后的提示框
                        this._shareFail()
                    } else {
                        let idx = Math.floor(Math.random() * this._shareFailTips.length);
                        let tip = this._shareFailTips[idx];
                        showModal({
                            title: tip.title, content: tip.content, showCancel: true, cancelText: '返回', cancelColor: '#666666',
                            confirmText: '去分享', fail: () => {
                                this._shareFail();
                                if (!!this._shareDefaultComplete) this._shareDefaultComplete();
                            }, success: () => {
                                debugLog('再分享');
                                this._callShare()
                            }
                        });
                        return;
                    }
                } else {
                    this._shareSuccess();
                }
            }
            if (!!this._shareDefaultComplete) this._shareDefaultComplete();
        }

        protected _shareSuccess() {
            debugLog('分享成功')
            if (!!this._successFun) this._successFun();
            this._successFun = null;
            this._failFun = null;
            if (!!this._shareDefaultSuccess) this._shareDefaultSuccess();
            this._shareContent = null;
            this._shareTotalTime = 0;
            this._shareCount = 0;
            this._readyShare = false;
        }

        protected _shareFail() {
            debugLog('分享失败');
            if (!!this._failFun) this._failFun();
            this._successFun = null;
            this._failFun = null;
            if (!!this._shareDefaultFail) this._shareDefaultFail();
            this._readyShare = false;
        }

    }
}